<!doctype html>
<html lang="zh-CN">
<head>
	<meta charset="utf-8">
	<title>Laravel - 为 WEB 艺术家创造的 PHP 框架。 | Laravel 中文网</title>
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="author" content="Laravel 中文网">
	<meta name="description" content="Laravel - 为 WEB 艺术家创造的 PHP 框架。| Laravel 中文网">
	<meta name="keywords" content="Laravel中文社区,php框架,laravel中文网,php framework,restful routing,laravel,laravel php">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<!--[if lte IE 9]>
		<script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
	<![endif]-->
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../../assets/css/laravel.css">
</head>
<body class="docs language-php">

	<span class="overlay"></span>

	<nav class="main">
		<div class="container">
			<a href="../../index.html" class="brand">
				<img src="../../assets/img/laravel-logo.png" height="30">
				Laravel
			</a>

			<div class="responsive-sidebar-nav">
				<a href="#" class="toggle-slide menu-link btn">&#9776;</a>
			</div>

				<div class="switcher">
					<div class="dropdown">
						<button class="btn dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
							<!--<span class="faint">v</span> -->
							4.1
							<span class="caret"></span>
						</button>
						<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
								<li role="presentation">
									<a role="menuitem" tabindex="-1" href="../5.0/index.html">5.0</a>
								</li>
								<li role="presentation">
									<a role="menuitem" tabindex="-1" href="../4.2/index.html">4.2</a>
								</li>
								<li role="presentation">
									<a role="menuitem" tabindex="-1" href="index.html">4.1</a>
								</li>
								<li role="presentation">
									<a role="menuitem" tabindex="-1" href="../4.0/index.html">4.0</a>
								</li>
						</ul>
					</div>
				</div>

			<ul class="main-nav">
				<li class="nav-docs"><a href="../index.html">中文文档</a></li>
				<li class="nav-community"><a href="http://wenda.golaravel.com" target="_blank">问答社区</a></li>
				<li class="nav-api"><a href="http://laravel.com/api/5.0/" target="_blank">API</a></li>
				<li class="nav-laracasts"><a href="https://laracasts.com" target="_blank">视频教程（国外）</a></li>
				<li class="nav-forge"><a href="https://forge.laravel.com" target="_blank">Forge</a></li>
				
			</ul>
		</div>
	</nav>

		<nav id="slide-menu" class="slide-menu" role="navigation">
		
		<div class="brand">
			<a href="../../index.html">
				<img src="../../assets/img/laravel-logo-white.png" height="50">
			</a>
		</div>

		<ul class="slide-main-nav">
			<li><a href="../../index.html">首页</a></li>
			<li class="nav-docs"><a href="../index.html">中文文档</a></li>
			<li class="nav-community"><a href="http://wenda.golaravel.com" target="_blank">问答社区</a></li>
			<li class="nav-api"><a href="http://laravel.com/api/5.0/" target="_blank">API</a></li>
			<li class="nav-laracasts"><a href="https://laracasts.com" target="_blank">视频教程（国外）</a></li>
			<li class="nav-forge"><a href="https://forge.laravel.com" target="_blank">Forge</a></li>
			
		</ul>

		<div class="slide-docs-nav">
			<h2>文档目录</h2>
			<ul>
<li>序言
<ul>
<li><a href="introduction.html">简介</a></li>
<li><a href="quick.html">快速入门</a></li>
<li><a href="releases.html">Release Notes</a></li>
<li><a href="upgrade.html">Upgrade Guide</a></li>
</ul>
</li>
<li>开始学习
<ul>
<li><a href="installation.html">安装</a></li>
<li><a href="configuration.html">配置</a></li>
<li><a href="lifecycle.html">Request的生命周期</a></li>
<li><a href="routing.html">路由</a></li>
<li><a href="requests.html">请求与输入</a></li>
<li><a href="responses.html">视图 &amp; Response</a></li>
<li><a href="controllers.html">控制器</a></li>
<li><a href="errors.html">错误 &amp; 日志</a></li>
</ul>
</li>
<li>深度历险
<ul>
<li><a href="security.html">Authentication</a></li>
<li><a href="cache.html">缓存</a></li>
<li><a href="extending.html">核心扩展</a></li>
<li><a href="events.html">事件</a></li>
<li><a href="facades.html">Facades</a></li>
<li><a href="html.html">表单 &amp; HTML</a></li>
<li><a href="helpers.html">有用的工具函数</a></li>
<li><a href="ioc.html">IoC 容器</a></li>
<li><a href="localization.html">本地化</a></li>
<li><a href="mail.html">邮件</a></li>
<li><a href="packages.html">扩展包开发</a></li>
<li><a href="pagination.html">分页</a></li>
<li><a href="queues.html">队列</a></li>
<li><a href="security.html">安全</a></li>
<li><a href="session.html">Session</a></li>
<li><a href="ssh.html">SSH</a></li>
<li><a href="templates.html">模板</a></li>
<li><a href="testing.html">单元测试</a></li>
<li><a href="validation.html">验证</a></li>
</ul>
</li>
<li>数据库
<ul>
<li><a href="database.html">基本用法</a></li>
<li><a href="queries.html">查询构造器</a></li>
<li><a href="eloquent.html">Eloquent ORM</a></li>
<li><a href="schema.html">结构生成器</a></li>
<li><a href="migrations.html">迁移 &amp; 数据填充</a></li>
<li><a href="redis.html">Redis</a></li>
</ul>
</li>
<li>Artisan 命令行工具
<ul>
<li><a href="artisan.html">概览</a></li>
<li><a href="commands.html">Artisan 开发</a></li>
</ul>
</li>
<li>贡献者
<ul>
<li><a href="contributors.html">中文翻译贡献者名单</a></li>
</ul>
</li>
</ul>

		</div>

	</nav>

	<div class="docs-wrapper container">

		<section class="sidebar">
			<ul>
<li>序言
<ul>
<li><a href="introduction.html">简介</a></li>
<li><a href="quick.html">快速入门</a></li>
<li><a href="releases.html">Release Notes</a></li>
<li><a href="upgrade.html">Upgrade Guide</a></li>
</ul>
</li>
<li>开始学习
<ul>
<li><a href="installation.html">安装</a></li>
<li><a href="configuration.html">配置</a></li>
<li><a href="lifecycle.html">Request的生命周期</a></li>
<li><a href="routing.html">路由</a></li>
<li><a href="requests.html">请求与输入</a></li>
<li><a href="responses.html">视图 &amp; Response</a></li>
<li><a href="controllers.html">控制器</a></li>
<li><a href="errors.html">错误 &amp; 日志</a></li>
</ul>
</li>
<li>深度历险
<ul>
<li><a href="security.html">Authentication</a></li>
<li><a href="cache.html">缓存</a></li>
<li><a href="extending.html">核心扩展</a></li>
<li><a href="events.html">事件</a></li>
<li><a href="facades.html">Facades</a></li>
<li><a href="html.html">表单 &amp; HTML</a></li>
<li><a href="helpers.html">有用的工具函数</a></li>
<li><a href="ioc.html">IoC 容器</a></li>
<li><a href="localization.html">本地化</a></li>
<li><a href="mail.html">邮件</a></li>
<li><a href="packages.html">扩展包开发</a></li>
<li><a href="pagination.html">分页</a></li>
<li><a href="queues.html">队列</a></li>
<li><a href="security.html">安全</a></li>
<li><a href="session.html">Session</a></li>
<li><a href="ssh.html">SSH</a></li>
<li><a href="templates.html">模板</a></li>
<li><a href="testing.html">单元测试</a></li>
<li><a href="validation.html">验证</a></li>
</ul>
</li>
<li>数据库
<ul>
<li><a href="database.html">基本用法</a></li>
<li><a href="queries.html">查询构造器</a></li>
<li><a href="eloquent.html">Eloquent ORM</a></li>
<li><a href="schema.html">结构生成器</a></li>
<li><a href="migrations.html">迁移 &amp; 数据填充</a></li>
<li><a href="redis.html">Redis</a></li>
</ul>
</li>
<li>Artisan 命令行工具
<ul>
<li><a href="artisan.html">概览</a></li>
<li><a href="commands.html">Artisan 开发</a></li>
</ul>
</li>
<li>贡献者
<ul>
<li><a href="contributors.html">中文翻译贡献者名单</a></li>
</ul>
</li>
</ul>

		</section>

		<article>
			<h1>数据库使用基础</h1>
<ul>
<li><a href="#configuration">配置</a></li>
<li><a href="#read-write-connections">Read / Write Connections</a></li>
<li><a href="#running-queries">执行查询语句</a></li>
<li><a href="#database-transactions">事务</a></li>
<li><a href="#accessing-connections">同时使用多个数据库系统</a></li>
<li><a href="#query-logging">查询日志</a></li>
</ul>
<p><a name="configuration"></a></p>
<h2>配置</h2>
<p>在Laravel中连接和使用数据库非常简单。 数据库配置在 <code>app/config/database.php</code> 文件中. 所有受支持的数据库系统都列在了配置文件中，在配置文件中可以同时配置多个数据库系统的连接信息, 并指定默认使用哪个数据库连接。</p>
<p>Laravel 目前支持四种数据库系统,分别是: MySQL， Postgres， SQLite， 和 SQL Server。</p>
<p><a name="read-write-connections"></a></p>
<h2>Read / Write Connections</h2>
<p>Sometimes you may wish to use one database connection for SELECT statements, and another for INSERT, UPDATE, and DELETE statements. Laravel makes this a breeze, and the proper connections will always be used whether you are using raw queries, the query builder, or the Eloquent ORM.</p>
<p>To see how read / write connections should be configured, let's look at this example:</p>
<pre><code>'mysql' =&gt; array(
    'read' =&gt; array(
        'host' =&gt; '192.168.1.1',
    ),
    'write' =&gt; array(
        'host' =&gt; '196.168.1.2'
    ),
    'driver'    =&gt; 'mysql',
    'database'  =&gt; 'database',
    'username'  =&gt; 'root',
    'password'  =&gt; '',
    'charset'   =&gt; 'utf8',
    'collation' =&gt; 'utf8_unicode_ci',
    'prefix'    =&gt; '',
),
</code></pre>
<p>Note that two keys have been added to the configuration array: <code>read</code> and <code>write</code>. Both of these keys have array values containing a single key: <code>host</code>. The rest of the database options for the <code>read</code> and <code>write</code> connections will be merged from the main <code>mysql</code> array. So, we only need to place items in the <code>read</code> and <code>write</code> arrays if we wish to override the values in the main array. So, in this case, <code>192.168.1.1</code> will be used as the &quot;read&quot; connection, while <code>192.168.1.2</code> will be used as the &quot;write&quot; connection. The database credentials, prefix, character set, and all other options in the main <code>mysql</code> array will be shared across both connections.</p>
<p><a name="running-queries"></a></p>
<h2>执行crud语句</h2>
<p>完成数据库配置后， 就可以直接使用DB类执行sql语句了.</p>
<h4>执行 select 语句</h4>
<p>$results = DB::select('select * from users where id = ?', array(1))；</p>
<p><code>select</code> 方法总是返回一个包含查询结果的 <code>array</code>。</p>
<h4>执行 Insert 语句</h4>
<pre><code>DB::insert('insert into users (id, name) values (?, ?)', array(1, 'Dayle'));
</code></pre>
<h4>执行 Update 语句</h4>
<pre><code>DB::update('update users set votes = 100 where name = ?', array('John'));
</code></pre>
<h4>执行 Delete 语句</h4>
<pre><code>DB::delete('delete from users');
</code></pre>
<blockquote>
<p><strong>注意:</strong> <code>update</code> 和 <code>delete</code> 语句返回操作所影响的数据的行数(int)。</p>
</blockquote>
<h4>执行非crud语句</h4>
<pre><code>DB::statement('drop table users');
</code></pre>
<h4>监听数据库操作事件</h4>
<p>可以使用 <code>DB::listen</code> 方法监听数据库操作:</p>
<pre><code>DB::listen(function($sql, $bindings, $time)
{
    //
});
</code></pre>
<p><a name="database-transactions"></a></p>
<h2>事务</h2>
<p>将需要在事务模式下执行的查询放入 <code>transaction</code> 方法内即可:</p>
<pre><code>DB::transaction(function()
{
    DB::table('users')-&gt;update(array('votes' =&gt; 1));

    DB::table('posts')-&gt;delete();
});
</code></pre>
<blockquote>
<p><strong>Note:</strong> Any exception thrown within the <code>transaction</code> closure will cause the transaction to be rolled back automatically.</p>
</blockquote>
<p>Sometimes you may need to begin a transaction yourself:</p>
<pre><code>DB::beginTransaction();
</code></pre>
<p>You can rollback a transaction via the <code>rollback</code> method:</p>
<pre><code>DB::rollback();
</code></pre>
<p>Lastly, you can commit a transaction via the <code>commit</code> method:</p>
<pre><code>DB::commit();
</code></pre>
<p><a name="accessing-connections"></a></p>
<h2>同时使用多个数据库系统</h2>
<p>有时可能需要同时使用多个数据库系统(MySQL，Postgres，SQLite，SQL Server), 通过DB类的 <code>DB::connection</code> 方法来切换:</p>
<pre><code>$users = DB::connection('foo')-&gt;select(...);
</code></pre>
<p>你可能需要在数据库系统的层面上操作数据库，使用PDO实例即可:</p>
<pre><code>$pdo = DB::connection()-&gt;getPdo();
</code></pre>
<p>使用reconnect方法重新连接一个指定的数据库系统：
DB::reconnect('foo');</p>
<p>If you need to disconnect from the given database due to exceeding the underyling PDO instance's <code>max_connections</code> limit, use the <code>disconnect</code> method:</p>
<pre><code>DB::disconnect('foo');
</code></pre>
<p><a name="query-logging"></a></p>
<h2>查询日志</h2>
<p>Laravel默认会为当前请求执行的的所有查询生成日志并保存在内存中。 因此， 在某些特殊的情况下， 比如一次性向数据库中插入大量数据， 就可能导致内存不足。 在这种情况下，你可以通过 <code>disableQueryLog</code> 方法来关闭查询日志：</p>
<pre><code>DB::connection()-&gt;disableQueryLog();
</code></pre>
<p>调用 <code>getQueryLog</code> 方法可以同时获取多个查询执行后的日志：</p>
<pre><code>   $queries = DB::getQueryLog();
</code></pre>

		</article>
	</div>


	<footer class="main">
		<ul>
			<li class="nav-docs"><a href="../index.html">中文文档</a></li>
			<li class="nav-community"><a href="http://wenda.golaravel.com" target="_blank">问答社区</a></li>
			<li class="nav-api"><a href="http://laravel.com/api/5.0/" target="_blank">API</a></li>
			<li class="nav-laracasts"><a href="https://laracasts.com" target="_blank">视频教程（国外）</a></li>
			<li class="nav-forge"><a href="https://forge.laravel.com" target="_blank">Forge</a></li>
			
		</ul>
		<p>Laravel is a trademark of Taylor Otwell. Copyright &copy; Taylor Otwell.</p>
		<p class="less-significant"><a href="http://jackmcdade.com" target="_blank">Design by Jack McDade</a></p>
	</footer>

	<script src="../../assets/js/laravel.js"></script>
	<script src="../../assets/js/viewport-units-buggyfill.js"></script>
	<script>window.viewportUnitsBuggyfill.init();</script>
	<script type="text/javascript">
	var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
	document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3Fc8d13872a523d9c286aa7affbe0921f1' type='text/javascript'%3E%3C/script%3E"));
	</script>
</body>
</html>
